import router from '@system.router'
import prompt from '@system.prompt'
import storage from '@system.storage'
import voice from '@system.voice'
import device from '@system.device'

export default {
  data: {
    title: '侦探大师',
    subtitle: '破解谜案，伸张正义',
    cases: [],
    playerData: null,
    settings: null,
    currentTime: '',
    weatherInfo: '',
    isVoiceMode: false
  },

  onInit() {
    this.loadData()
    this.updateTime()
    this.getWeatherInfo()
    this.checkDeviceFeatures()
  },

  onShow() {
    this.loadData()
  },

  loadData() {
    // 加载案件数据
    storage.get({
      key: 'cases',
      success: (data) => {
        if (data) {
          this.cases = JSON.parse(data.data || data)
        }
      }
    })

    // 加载玩家数据
    storage.get({
      key: 'playerData',
      success: (data) => {
        if (data) {
          this.playerData = JSON.parse(data.data || data)
        }
      }
    })

    // 加载设置
    storage.get({
      key: 'settings',
      success: (data) => {
        if (data) {
          this.settings = JSON.parse(data.data || data)
        }
      }
    })
  },

  updateTime() {
    const now = new Date()
    this.currentTime = now.toLocaleString('zh-CN')
    setInterval(() => {
      const now = new Date()
      this.currentTime = now.toLocaleString('zh-CN')
    }, 1000)
  },

  getWeatherInfo() {
    // 获取天气信息（模拟）
    const weatherConditions = ['晴朗', '多云', '阴天', '小雨', '大雨']
    const randomWeather = weatherConditions[Math.floor(Math.random() * weatherConditions.length)]
    this.weatherInfo = `天气: ${randomWeather}`
  },

  checkDeviceFeatures() {
    // 检查设备功能
    device.getInfo({
      success: (info) => {
        console.info('Device info:', info)
        if (info.deviceType === 'wearable') {
          this.isVoiceMode = true
        }
      }
    })
  },

  startNewCase(caseId) {
    const selectedCase = this.cases.find(c => c.id === caseId)
    if (selectedCase && selectedCase.unlocked) {
      router.push({
        uri: 'pages/caseDetail/caseDetail',
        params: { caseId: caseId }
      })
    } else {
      prompt.showToast({
        message: '该案件尚未解锁',
        duration: 2000
      })
    }
  },

  continueInvestigation() {
    // 继续上次调查
    storage.get({
      key: 'currentCase',
      success: (data) => {
        if (data) {
          const currentCase = JSON.parse(data.data || data)
          router.push({
            uri: 'pages/interrogation/interrogation',
            params: { caseId: currentCase.id }
          })
        } else {
          prompt.showToast({
            message: '没有进行中的案件',
            duration: 2000
          })
        }
      }
    })
  },

  openStatistics() {
    router.push({
      uri: 'pages/statistics/statistics'
    })
  },

  openSettings() {
    router.push({
      uri: 'pages/settings/settings'
    })
  },

  openAchievements() {
    router.push({
      uri: 'pages/achievements/achievements'
    })
  },

  startVoiceRecognition() {
    if (this.settings && this.settings.voiceRecognition) {
      voice.startListening({
        success: (result) => {
          this.handleVoiceCommand(result.text)
        },
        fail: (error) => {
          prompt.showToast({
            message: '语音识别失败: ' + error.message,
            duration: 2000
          })
        }
      })
    }
  },

  handleVoiceCommand(command) {
    const lowerCommand = command.toLowerCase()
    if (lowerCommand.includes('开始') && lowerCommand.includes('案件')) {
      const caseNumber = this.extractCaseNumber(command)
      if (caseNumber) {
        this.startNewCase(caseNumber)
      }
    } else if (lowerCommand.includes('统计')) {
      this.openStatistics()
    } else if (lowerCommand.includes('设置')) {
      this.openSettings()
    }
  },

  extractCaseNumber(command) {
    const numbers = command.match(/\d+/)
    return numbers ? parseInt(numbers[0]) : null
  },

  onMenuPress() {
    // 菜单按钮点击事件
    prompt.showContextMenu({
      itemList: ['案件列表', '统计信息', '成就', '设置', '帮助'],
      success: (result) => {
        switch (result.index) {
          case 0:
            this.showCaseList()
            break
          case 1:
            this.openStatistics()
            break
          case 2:
            this.openAchievements()
            break
          case 3:
            this.openSettings()
            break
          case 4:
            this.showHelp()
            break
        }
      }
    })
  },

  showCaseList() {
    router.push({
      uri: 'pages/caseList/caseList'
    })
  },

  showHelp() {
    router.push({
      uri: 'pages/help/help'
    })
  }
}